//
//  HealthTool.swift
//  CheckmeRing
//
//  Created by 董鹏 on 2022/3/27.
//

import UIKit
import HealthKit

class HealthTool: NSObject {

    /// 判断权限
    class func openPermissions() {
        
        let typestoShare = Set([
            HKObjectType.quantityType(forIdentifier: .oxygenSaturation)!,
            HKObjectType.quantityType(forIdentifier: .heartRate)!])
        if HKHealthStore.isHealthDataAvailable() {
            let healthStore = HKHealthStore.init()
            healthStore.requestAuthorization(toShare: typestoShare, read: nil) { success, error in
                
            }
            
            print(healthStore.authorizationStatus(for: HKObjectType.quantityType(forIdentifier: .heartRate)!))
            
        }else {
            
        }
    }
    
    class func uploadDataToAppleHealth(datas: [RModel]) {
        if datas.count == 0 {
            return
        }
        
        /// 不上传
        if CacheManager.manager.getValueForKey(AppleHealthUpload) as? Bool == false {
            return
        }
        print("上传苹果健康数据")
        let typestoShare = Set([
            HKObjectType.quantityType(forIdentifier: .oxygenSaturation)!,
            HKObjectType.quantityType(forIdentifier: .heartRate)!])
        
        
        if HKHealthStore.isHealthDataAvailable() {
            
            let healthStore = HKHealthStore.init()
            
            healthStore.requestAuthorization(toShare: typestoShare, read: nil) { success, error in
                
                if success {
                    
                    var hkObject = [HKObject]()
                    
                    // 心跳总数
                    var sumHeartRate = 0
                    
                    for obj in datas {
                        // 时间
                        let time = Date(timeIntervalSince1970: obj.timeStamp)
                        // 血氧单位 按百分比算
                        let spo2Unit = HKUnit.percent().unitDivided(by: HKUnit.percent())
                        // 单位时间内血氧数
                        let spo2CountUnitQuantity = HKQuantity.init(unit: spo2Unit, doubleValue: Double(Double(obj.spo2) / 100.0))
                        // 健康类型：血氧
                        let spo2Type = HKObjectType.quantityType(forIdentifier: .oxygenSaturation)!
                        
                        // 一个要写入的血氧数据
                        let spo2CountSample = HKQuantitySample.init(type: spo2Type, quantity: spo2CountUnitQuantity, start: time, end: time)
                        hkObject.append(spo2CountSample)
                        
                        sumHeartRate += obj.hr
                    }
                    
                    // 写入心率
                    // 单位
                    let countUnit = HKUnit.count().unitDivided(by: HKUnit.minute())
                    // 单位时间内心跳数
                    let hrCountUnitQuantity = HKQuantity.init(unit: countUnit, doubleValue: Double(sumHeartRate / datas.count))
                    // 健康类型：心跳
                    let heartRateType = HKQuantityType.quantityType(forIdentifier: .heartRate)
                    // 一个要写入的心跳数据
                    let heartCountSample = HKQuantitySample.init(type: heartRateType!, quantity: hrCountUnitQuantity, start: Date(), end: Date())
                    hkObject.append(heartCountSample)
                    
                    healthStore.save(hkObject) { isSuccess, errors in
                        if isSuccess {
                            print("上传苹果健康成功")
                        }else {
//                            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
//                                getCurrentViewController()?.view.showYCToast(message: "上传苹果健康失败")
//                            }
                        }
                    }
                }
                
            }
        }
    }
    
}
